package com.example.tms.controller;

import com.example.tms.bean.FileInfo;
import com.example.tms.bean.ReturnInfo;
import com.example.tms.mapper.FileMapper;
import com.example.tms.tools.GlobalParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;
import com.example.tms.annotation.*;
/**
 * 文件操作
 */
@RestController
public class FileController  extends WebMvcConfigurerAdapter {

    private final FileMapper fileMapper;

    @Autowired
    public FileController(FileMapper fileMapper){
        this.fileMapper = fileMapper;
    }

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${file.uploadFolder}")
    private String path;

    @Value("${file.staticAccessPath}")
    private String staticAccessPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + path);
    }


    //查询文件列表信息（所属id）
    @RequestMapping(value = "/files/all/{ownerid}", method = RequestMethod.GET)
    public ReturnInfo findFiles(@PathVariable("ownerid") String ownerid){
        return ReturnInfo.info2(fileMapper.findByOwneridAndSfczOrderByUploadtimeDesc(ownerid,true));
    }

    //查询文件信息（文件id）
    @RequestMapping(value = "/files/{fileid}", method = RequestMethod.GET)
    public FileInfo findFile(@PathVariable("fileid") String fileid){
        return fileMapper.findOne(fileid);
    }

    //文件上传
    @MonitorRequest
    @RequestMapping(value = "/files", method = RequestMethod.POST)
    public ReturnInfo uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest httpServletRequest){
//        String classPath = this.getClass().getClassLoader().getResource("").getPath();
//        String path = classPath+"static/files/";
        path=path.replaceAll("%20"," ");
        String tablename = httpServletRequest.getParameter("tablename");
        String ownerid = httpServletRequest.getParameter("ownerid");
        String fileid = httpServletRequest.getParameter("fileid");
        if (file.isEmpty()) {
            return ReturnInfo.info3("文件为空", "", "");
        }
        //获取文件名
        String fileName = file.getOriginalFilename();
        String hzm = fileName.substring(fileName.indexOf("."));
        // 文件上传后的路径
        String fileUrl = tablename+"/"+ownerid+"/"+UUID.randomUUID().toString().replaceAll("-","")+hzm;
        logger.info(fileUrl);
        File dest = new File(path + fileUrl);
        //创建父文件路径
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            FileInfo fileInfo = new FileInfo(fileid,ownerid,fileName,fileUrl,tablename);
            fileMapper.save(fileInfo);
            logger.info("上传文件"+fileInfo.toString());
            return ReturnInfo.info3("上传成功", fileName,fileUrl);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        return ReturnInfo.info3("上传失败", "", "");
    }

    //文件下载
    @RequestMapping(value = "/files", method = RequestMethod.GET)
    public ReturnInfo downloadFile(HttpServletResponse response, HttpServletRequest request){
        String fileid = request.getParameter("fileid");
        if (fileid != null&&!fileid.equals("")) {
//            String classPath = this.getClass().getClassLoader().getResource("").getPath();
//            String path = classPath.substring(0,classPath.indexOf(GlobalParam.filesposition))+"files/";
//            String path = classPath+"static/files/";
            path=path.replaceAll("%20"," ");
            FileInfo fileInfo = fileMapper.findOne(fileid);
            File file = new File(path, fileInfo.getFileurl());
            String fileName = fileInfo.getFilename();
            try {
                fileName = new String(fileName.getBytes(), "ISO-8859-1");
            }
            catch(Exception e) {
                e.printStackTrace();
            }
            if (file.exists()) {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    logger.info("文件下载"+fileid);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

    //文件删除
    @MonitorRequest
    @RequestMapping(value = "/files/{fileid}", method = RequestMethod.DELETE)
    public ReturnInfo deleteFile(@PathVariable String fileid){
        if (fileid != null&&!fileid.equals("")) {
            FileInfo fileInfo = fileMapper.findOne(fileid);
//            String classPath = this.getClass().getClassLoader().getResource("").getPath();
//            String path = classPath.substring(0,classPath.indexOf(GlobalParam.filesposition))+"files/";
//            String path = classPath+"static/files/";
            path=path.replaceAll("%20"," ");
            String b = GlobalParam.deleteF(fileInfo, path).getMessage();
            if(b.equals("删除成功！")){
                fileMapper.delete(fileid);
                logger.info("文件删除"+fileid);
            }
            return ReturnInfo.info1(b);
//            File file = new File(path, fileInfo.getFileurl());
//            if(file.exists()){
//                if(!file.delete()){
//                    return ReturnInfo.info1("删除失败！");
//                }
//                fileMapper.delete(fileid);
//                return ReturnInfo.info1("删除成功！");
//            }else {
//                return ReturnInfo.info1("文件不存在！");
//            }
        }else {
            return ReturnInfo.info1("文件目录错误！");
        }
    }

    //文件转移
    public void copyFile(String oldPath, String newPath) {
//        String classPath = this.getClass().getClassLoader().getResource("").getPath();
//        String path = classPath.substring(0,classPath.indexOf(GlobalParam.filesposition))+"file/";
//        String path = classPath+"static/files/";
        path=path.replaceAll("%20"," ");
        oldPath = path+oldPath;
        newPath = path+newPath;
        File oldfile = new File(oldPath);
        File newfile = new File(newPath);
        System.out.println(oldPath+"   "+newPath);
        try {
            int byteread = 0;
            if (oldfile.exists()) { //文件存在时
                if(!newfile.getParentFile().exists()){
                    newfile.getParentFile().mkdirs();
                }
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                while ( (byteread = inStream.read(buffer)) != -1) {
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
                fs.close();
                oldfile.delete();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    //文件夹删除
    private boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list(); //递归删除目录中的子目录下
            assert children != null;
            for (String aChildren : children) {
                boolean success = deleteDir(new File(dir, aChildren));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete(); // 目录此时为空，可以删除
    }

}
